# -*- coding: utf-8 -*-
import hashlib

import requests
from django.conf import settings

from async import async_job
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '88050': {
        # dwc 微信h5:费率3.8%(30 50 100 200 300 500 固定金额 ) D0结算
        # dwc 微信扫码:费率3.5%（100---5000) D0结算
        'API_KEY': '010E616305FF68DFD8B38BDAD45FB6F5',
        'gateway': 'http://43.227.196.168:82/interface/chargebank.aspx',
        'query_gateway': 'http://43.227.196.168:82/pay/Query.aspx?parter={}&type={}&orderid={}&sign={}',
    },
    '88059': {
        # dwc 微信h5:费率3.8%(30 50 100 200 300 500 固定金额 ) D0结算
        'API_KEY': '5F08B8A7F4FC94EE13D28A6D509EFA68',
        'gateway': 'http://43.227.196.168:82/interface/chargebank.aspx',
        'query_gateway': 'http://43.227.196.168:82/pay/Query.aspx?parter={}&type={}&orderid={}&sign={}',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def gen_order_str(parameter):
    return 'parter={}&type={}&orderid={}&callbackurl={}'.format(
        parameter['parter'], parameter['type'],
        parameter['orderid'], parameter['callbackurl'])


def generate_order_sign(parameter, key):
    s = gen_order_str(parameter) + key
    m = hashlib.md5()
    m.update(s.encode('GB2312'))
    sign = m.hexdigest()
    return sign


def generate_query_sign(parameter, key):
    s = 'parter={}&type={}&orderid={}&key={}'.format(parameter['parter'], parameter['type'], parameter['orderid'], key)
    m = hashlib.md5()
    m.update(s.encode('GB2312'))
    sign = m.hexdigest()
    return sign


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    s = 'orderid={}&restate={}&ovalue={}{}'.format(params['orderid'], params['restate'], params['ovalue'], key)
    m = hashlib.md5()
    m.update(s.encode('GB2312'))
    calculated_sign = m.hexdigest()
    if sign != calculated_sign:
        _LOGGER.info("un2pay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 快捷支付	KUAIJIE
# 微信扫码支付	WEIXIN
# 微信H5支付	WXWAP
# 微信公众号支付	WXAPP
# 支付宝H5支付	ALIWAP
# QQ钱包扫码支付	QQCODE
# QQ钱包H5支付	QQWAP
# QQ钱包公众号支付	QQAPP
# 京东扫码支付	JINGDONG
# 京东H5支付	JDWAP
def _get_pay_type(service):
    if service == 'wechat_h5':
        return 'WXWAP'
    elif service == 'alipay':
        return 'ALIWAP'
    elif service == 'qq':
        return 'QQWAP'
    elif service == 'jd':
        return 'JDWAP'
    elif service == 'wechat_scan':
        return 'WEIXIN'
    elif service == 'wechat_pub':
        return 'WXAPP'
    else:
        return 'KUAIJIE'


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    key = _get_api_key(app_id)
    service = info.get('service')
    p_dict = {
        'parter': app_id,
        'type': _get_pay_type(service),
        'value': pay_amount,
        'orderid': str(pay.id),
        'callbackurl': '{}/pay/api/{}/un2pay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id),
        'hrefbackurl': '{}/pay/api/{}/un2pay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))
    }
    sign = generate_order_sign(p_dict, key)
    url = _get_gateway(app_id) + '?' + gen_order_str(p_dict) + '&value=' + str(pay_amount) + '&sign=' + sign
    _LOGGER.info("un2pay data url: %s", url)
    return {'charge_info': url}


# ok
def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("un2pay notify data: %s", data)
    verify_notify_sign(data, key)
    pay_id = data['orderid']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('un2pay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['restate'])
    trade_no = ''
    total_fee = float(data['ovalue'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 0 成功， 其他失败
    if trade_status == 0:
        _LOGGER.info('un2pay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return ''


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    p_dict = {
        'parter': app_id,
        'type': 1,
        'orderid': str(pay_id),
    }
    p_dict['sign'] = generate_query_sign(p_dict, key)
    url = _get_query_gateway(app_id).format(p_dict['parter'], p_dict['type'], p_dict['orderid'], p_dict['sign'])
    _LOGGER.info(u'un2pay create query url : %s', url)
    response = requests.get(url)
    _LOGGER.info(u'un2pay create query rsp: %s', response.text)
    if response.status_code == 200:
        trade_status = int(_get_str(response.text, 'ordstate=', '&'))
        total_fee = float(_get_str(response.text, 'ordamt=', '&'))
        trade_no = ''
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 0订单处理中， 1支付成功， 2失败
        if trade_status == 1:
            _LOGGER.info('un2pay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('un2pay data error, status_code: %s', response.status_code)
